const SERVER_URL = process.env.VUE_APP_API_URL
const RESOURCE_URL = process.env.VUE_APP_RESOURCE_URL
const API_SECRET_KEY = 'liangboceo'
import util from '@/utils/util'
import { hex_md5 } from '@/utils/md5'
import request from '@/utils/axios'
import ServerConstants from '@/utils/ServerConstants'
import {
  setStore,
  getStore,
  removeStore,
  addCookie,
  getCookie,
  delCookie,
} from '@/utils/storage'

import { saveCart, delCart, getCart, delCartIndex } from '@/api/cart'

import store from '@/store/index'

import { encode } from 'js-base64/base64'

let setting = {}
let axios = request()
export default class server {
  static vue

  static initVue (vue) {
    server.vue = vue
  }

  static __args () {
    if (arguments.length === 1 && typeof arguments[0] !== 'string') {
      setting = arguments[0]
    } else {
      setting.url = arguments[0]
      if (typeof arguments[1] === 'object') {
        /*为了解决js对象引用导致的数据被修改的问题*/
        setting.data = JSON.parse(JSON.stringify(arguments[1]))
        if (server._isEmpty(server.getUserInfo())) {
          setting.data.token = ''
        } else {
          setting.data.token = server.getUserInfo().token
        }
        let str = util.ksort(setting.data)
        let strafter = ''
        for (let i in str) {
          strafter += str[i]
        }
        setting.data.time = (new Date()).getTime()
        setting.data.sign = hex_md5(this.utf8(strafter) + setting.data.time +
          API_SECRET_KEY)
        setting.success = arguments[2]
      } else {
        setting.success = arguments[1]
      }
    }
    if (setting.url.indexOf('http://') !== 0 ||
      setting.url.indexOf('https://') !== 0) {
      setting.url = SERVER_URL + setting.url
    }
    return setting
  }

  static __json (method, setting, time = 1) {
    setting.method = method
    setting.headers = {
      'content-type': 'application/x-www-form-urlencoded',
      'Origin': SERVER_URL,
    }

    if (setting.method === 'GET') {
      return axios.get(setting.url, {params: setting.data}).
        then(setting.success, function (error) {
          console.log(error)
        })
    }
    return axios.post(setting.url, {data: setting.data}).
      then(setting.success, function (error) {
        console.log(error)
      })
  }

  static getJSON () {
    this.__json('GET', this.__args.apply(this, arguments))
  }

  static sendTemplate (mobile, type, callback) {
    this.getJSON(ServerConstants.REQ_SEND_MSG, {send: mobile, type: type},
      callback)
  }

  static utf8 (inputStr) { //将中文转为UTF8
    let outputStr = ''
    for (let i = 0; i < inputStr.length; i++) {
      let temp = inputStr.charCodeAt(i)
      if (temp < 128) {
        outputStr += String.fromCharCode(temp)
      }
      else if (temp < 2048) {
        outputStr += String.fromCharCode((temp >> 6) | 192)
        outputStr += String.fromCharCode((temp & 63) | 128)
      }
      else if (temp < 65536) {
        outputStr += String.fromCharCode((temp >> 12) | 224)
        outputStr += String.fromCharCode(((temp >> 6) & 63) | 128)
        outputStr += String.fromCharCode((temp & 63) | 128)
      }
      else {
        outputStr += String.fromCharCode((temp >> 18) | 240)
        outputStr += String.fromCharCode(((temp >> 12) & 63) | 128)
        outputStr += String.fromCharCode(((temp >> 6) & 63) | 128)
        outputStr += String.fromCharCode((temp & 63) | 128)
      }
    }
    return outputStr
  }

  static postJSON () {
    this.__json('POST', this.__args.apply(this, arguments))
  }

  static sleep (s) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('promise resolved')
      }, s * 1000)
    })
  }

  static logo () {
    /*用于reload整个js的代码,放在前面*/
    console.log('//\n' +
      '//                            _ooOoo_\n' +
      '//                           o8888888o\n' +
      '//                           88" . "88\n' +
      '//                           (| -_- |)\n' +
      '//                            O\\ = /O\n' +
      '//                        ____/`---\'\\____\n' +
      '//                      .   \' \\\\| |// `.\n' +
      '//                       / \\\\||| 2 |||// \\\n' +
      '//                     / _||||| -0- |||||- \\\n' +
      '//                       | | \\\\\\ 1 /// | |\n' +
      '//                     | \\_| \'\'\\-9-/\'\' | |\n' +
      '//                      \\ .-\\__ `0` ___/-. /\n' +
      '//                   ___`. .\' /--5--\\ `. . __\n' +
      '//                ."" \'< `.___\\_<2>_/___.\' >\'"".\n' +
      '//               | | : `- \\`.;`\\ 0 /`;.`/ - ` : | |\n' +
      '//                 \\ \\ `-. \\_ __\\ /__ _/ .-` / /\n' +
      '//         ======`-.____`-.___\\_____/___.-`____.-\'======\n' +
      '//                            `=---=\'\n' +
      '//\n' +
      '//         .............................................\n' +
      '//                  佛祖保佑------  永无BUG\n' +
      '//          佛曰:\n' +
      '//                  城阙辅三秦，风烟望五津。\n' +
      '//                  与君离别意，同是宦游人。\n' +
      '//                  海内存知己，天涯若比邻。\n' +
      '//                  无为在歧路，儿女共沾巾。\n' +
      '// by the jackliang【qq:173120209,phone:15501581959】 ')

    console.log(process.env)
    server.vue.prototype.$store.commit('setHaslogin', server.islogin())
    server.vue.prototype.$store.commit('setUserInfo', server.getUserInfo())
    server.vue.prototype.$store.commit('setCartInfo', server.getCartInfo())
  }

  static getVerify (type) {
    return SERVER_URL + ServerConstants.REQ_GET_VERIFY + '?type=' + type +
      '&time=' + (new Date()).getTime()
  }

  static saveUserInfo (result) {
    setStore(ServerConstants.USER_INFO, result)
    server.updateRefresh(ServerConstants.USER_INFO_REFRESH, 1)
  }

  static delUserInfo () {
    removeStore(ServerConstants.USER_INFO)
    server.updateRefresh(ServerConstants.USER_INFO_REFRESH, 1)
  }

  static getUserInfo () {
    if (server._isEmpty(getStore(ServerConstants.USER_INFO))) {
      return getStore(ServerConstants.USER_INFO)
    }
    return JSON.parse(getStore(ServerConstants.USER_INFO))
  }

  static addCartInfo (result) {
    let oldCart = server.getCartInfo()
    let newcart = []
    if (server._isEmpty(oldCart) || oldCart.length <= 0) {
      newcart = result
    } else {
      newcart = oldCart.concat(result)
    }
    let set = []
    newcart.forEach(item => {
      if (set.length <= 0) {
        set.push(item)
      } else {
        let model = server.getSameModel(item, set)
        if (server._isEmpty(model) || model.length <= 0) {
          set.push(item)
        } else {
          set.map(function (goal, index) {
            if (goal.type === item.type && goal.goods_id === item.goods_id &&
              goal.id === item.id) {
              item.count = set[index].count + item.count
              set[index] = item
            }
          })
        }
      }
    })
    if (server.islogin()) {
      saveCart(set, function (res) {
        if (parseInt(res.data.status) === 0) {
          server.vue.prototype.$store.commit('setCartInfo', res.data.result)
          setStore(ServerConstants.CART_INFO, res.data.result)
          server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
        }
      })
    } else {
      server.vue.prototype.$store.commit('setCartInfo', set)
      setStore(ServerConstants.CART_INFO, set)
      server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
    }
  }

  static saveCartInfo (result) {
    if (server.islogin()) {
      saveCart(result, function (res) {
        if (parseInt(res.data.status) === 0) {
          server.vue.prototype.$store.commit('setCartInfo', res.data.result)
          setStore(ServerConstants.CART_INFO, res.data.result)
          server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
        }
      })
    } else {
      server.vue.prototype.$store.commit('setCartInfo', result)
      setStore(ServerConstants.CART_INFO, result)
      server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
    }

  }

  static getSameModel (item, set) {
    return set.filter(v => {
      if (v.type === item.type && v.goods_id === item.goods_id &&
        v.id === item.id) {
        return v
      }
    })
  }

  static delCartInfo () {
    if (server.islogin()) {
      delCart({}, function (res) {
        if (parseInt(res.data.status) === 0) {
          server.vue.prototype.$store.commit('setCartInfo', {})
          removeStore(ServerConstants.CART_INFO)
          server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
        }
      })
    } else {
      server.vue.prototype.$store.commit('setCartInfo', {})
      removeStore(ServerConstants.CART_INFO)
      server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
    }

  }

  static delCartInfoIndex (row, result) {
    if (server.islogin()) {
      delCartIndex({id: row.dbid}, function (res) {
        if (parseInt(res.data.status) === 0) {
          server.vue.prototype.$store.commit('setCartInfo', res.data.result)
          setStore(ServerConstants.CART_INFO, res.data.result)
          server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
        }
      })
    } else {
      server.vue.prototype.$store.commit('setCartInfo', result)
      setStore(ServerConstants.CART_INFO, result)
      server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
    }
  }

  static getCartInfo () {
    let localCart = []
    if (!server._isEmpty(getStore(ServerConstants.CART_INFO))) {
      localCart = JSON.parse(getStore(ServerConstants.CART_INFO))
    }
    return localCart
  }

  static initCartInfo () {
    let localCart = []
    if (!server._isEmpty(getStore(ServerConstants.CART_INFO))) {
      localCart = JSON.parse(getStore(ServerConstants.CART_INFO))
    }
    if (server.islogin()) {
      getCart(function (res) {
        if (parseInt(res.data.status) === 0) {
          server.vue.prototype.$store.commit('setCartInfo', res.data.result)
          setStore(ServerConstants.CART_INFO, res.data.result)
          server.updateRefresh(ServerConstants.CART_INFO_REFRESH, 1)
        }
      })
    }
    return localCart
  }

  static getSystemInfo () {
    return JSON.parse(getStore(ServerConstants.SYSTEM_INFO))
  }

  static saveSystemInfo (result) {
    setStore(ServerConstants.SYSTEM_INFO, result)
  }

  static updateRefresh (k, v) {
    let result = server.getRefresh()
    result[k] = v
    setStore(ServerConstants.SYSTEM_REFRESH, result)
  }

  static refresh (k) {
    if (server._isEmpty(getStore(ServerConstants.SYSTEM_REFRESH))) {
      return false
    }
    let json = JSON.parse(getStore(ServerConstants.SYSTEM_REFRESH))
    if (server._isEmpty(json[k])) {
      return false
    }
    return parseInt(json[k]) === 1
  }

  static getRefresh () {
    if (server._isEmpty(getStore(ServerConstants.SYSTEM_REFRESH))) {
      return {}
    }
    return JSON.parse(getStore(ServerConstants.SYSTEM_REFRESH))
  }

  static saveNewOrderNumber (count) {
    setStore(ServerConstants.ORDER_COUNT, parseInt(count))
  }

  static getNewOrderNumber () {
    return parseInt(getStore(ServerConstants.ORDER_COUNT))
  }

  static saveTime (time) {
    setStore(ServerConstants.ORDER_TIME, parseInt(time))
  }

  static getTime () {
    return parseInt(getStore(ServerConstants.ORDER_TIME))
  }

  static savePrint (result) {
    setStore(ServerConstants.PRINT_LIST, result)
  }

  static getPrint () {
    return getStore(ServerConstants.PRINT_LIST, true)
  }

  static saveDefautDevice (adress) {
    setStore(ServerConstants.DEFAULT_PRINT, adress)
  }

  static getDefautDevice () {
    return getStore(ServerConstants.DEFAULT_PRINT)
  }

  static fixUrl (url) {
    if (server._isEmpty(url)) {
      return url
    }
    if (url.indexOf('http://') !== 0 &&
      url.indexOf('https://') !== 0) {
      url = RESOURCE_URL + url
    }
    return url
  }

  static _isEmpty (input) {
    return input + '' === 'null' || input + '' === 'undefined' || input === ''
  }

  static islogin () {
    if (server._isEmpty(server.getUserInfo()) ||
      server._isEmpty(server.getUserInfo().token)) {
      return false
    }
    return true
  }

  static checkLogin () {
    if (server._isEmpty(server.getUserInfo()) ||
      server._isEmpty(server.getUserInfo().token)) {
      server.wxlogin()
      return
    }
    let s = server
    server.postJSON(ServerConstants.REQ_GET_USERINFO,
      {token: server.getUserInfo().token}, function (res) {
        if (parseInt(res.data.status) !== 1) {
          server.wxlogin()
          return
        }
        server.vue.prototype.$store.commit('login', res.data.result)
      })
  }

  static wxlogin () {
    uni.getProvider({
      service: 'oauth',
      success: function (res) {
        if (~res.provider.indexOf('weixin')) {
          uni.authorize({
            scope: 'scope.userInfo',
            success () {
              uni.getUserInfo({
                provider: 'weixin',
                success: function (infoRes) {
                  server.dowxlogin(infoRes.userInfo)
                },
              })
            }, fail () {
              uni.navigateTo({
                url: `/pages/public/authorize`,
              })
            },
          })
        } else {
          uni.navigateTo({
            url: '/pages/public/login',
          })
        }
      },
    })
  }

  static dowxlogin (user) {
    uni.login({
      provider: 'wechat',
      success: function (loginRes) {
        if (server._isEmpty(loginRes.code)) {
          return
        }
        server.postJSON(ServerConstants.REQ_USER_LOGIN_OAUTH,
          {code: loginRes.code, ...user}, function (result) {
            server.msg(result.data.msg)
            if (parseInt(result.data.status) === 1) {
              server.vue.prototype.$store.commit('login', result.data.result)
              uni.switchTab({
                url: `/pages/user/user`,
              })
            }
          })
      },
    })
  }

  static dologout () {
    server.delUserInfo()
    server.checkLogin()
  }

  static fixResult () {

  }

  static msg (title) {
    server.showToast(title)
  }

  static successMsg (title) {
    server.showToast(title, 1500, false, 'success')
  }

  static loadingMsg (title) {
    server.showToast(title, 1500, false, 'loading')
  }

  static showToast (title, duration = 1500, mask = false, icon = 'none') {
    if (Boolean(title) === false) {
      return
    }
    uni.showToast({
      title,
      duration,
      mask,
      icon,
    })
  }

  static call (fn, response) {
    if (!server._isEmpty(fn) && typeof fn === 'function') {
      if (!server._isEmpty(response)) {
        return fn(response)
      } else {
        return fn()
      }
    }
  }

  static encode (data) {
    return encode(JSON.stringify(data))
  }

  static getSystem () {
    return uni.getSystemInfoSync()
  }

  static getOpenId () {
    if (server._isEmpty(server.getUserInfo()) ||
      server._isEmpty(server.getUserInfo().openid)) {
      return ''
    }
    return server.getUserInfo().openid
  }

}

